package com.pan.crawler.impl5;

import com.pan.crawler.Page;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.List;

public class PageImpl5 implements Page {

    private EdgeDriver edgeDriver;

    public PageImpl5() {
        edgeDriver = new EdgeDriver();
        edgeDriver.manage().window().minimize();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    }

    private final String[][]replaceStr;{
        replaceStr = new String[][]{
                {"\n\n"},//old char
                {"\n"}//new char
        };
    }
    public String clear(String content){
        for (int i = 0; i < replaceStr[0].length; i++) {
            content = content.replace(replaceStr[0][i],replaceStr[1][i]);
        }
        return  content;
    }

    @Override
    public String get(Chapter chapter) {
        String url = chapter.getUrl();
        String title = "\n\n\n\n\n\n\n\n"
                +"第"+(chapter.getId()+1)+"章 "
                +chapter.getTitle().replaceAll("^\\d+","")
                +chapter.getTitle().replaceAll("第\\p{all}+章","")
                +"\n\n\n\n\n";
        edgeDriver.navigate().to(url);
        WebElement contentElement = edgeDriver.findElement(By.className("contentbox"));
        String content = contentElement.getText();
        List<WebElement> strongList = contentElement.findElements(By.cssSelector("strong"));
        String target = "本章有错误，我要提交\n" +
                "上一章 返回目录 下一章\n" +
                "小提示：按 回车[Enter]键 返回书目，按 ←键 返回上一页， 按 →键 进入下一页。\n";
        target = strongList.stream().map(strong->strong.getText()).reduce((x,y)->x+"\n"+y).get()+"\n"
                +target+contentElement.findElement(By.className("tuijian_new")).getText();
        content = content.replace(target,"");
        content = clear(content);
//        不要带标题
//        return title+content;
        return content;
    }

    @Override
    public void close() {
        edgeDriver.quit();
    }
}
